#-*-coding:utf-8-*-
# Create your views here.
from models import Agent
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator

"""保存信息"""
def save (request):
    """管理员才有权限"""
    if request.session['level'] != "administrators":
        return HttpResponseRedirect('/')
    if request.method == 'POST':
            new_data = request.POST.copy()
            if new_data.has_key('id'):
                agent = Agent.objects.get(pk = new_data['id'])
                agent.name = new_data['name']
                agent.budget = new_data['budget']
                agent.intro = new_data['intro']
            else:
                agent = Agent(
                name = new_data['name'],
                budget = new_data['budget'],
                intro = new_data['intro'],
                )
            agent.save()
    return HttpResponseRedirect('/alist/')


"""Agents列表"""
def alist(request, page = '1'):
    """管理员才有权限"""
    if request.session['level'] != "administrators":
        return HttpResponseRedirect('/')
    agent = Agent.objects.order_by('id')
    paginator = Paginator(agent, 10)
    try:
        page = int(page)
#        page = int(request.GET.get('page','1'))
        agent = paginator.page(page)
    except:
        return HttpResponseRedirect('/alist', {'level':request.session['level']})

    return render_to_response('alist.html', {
    'paginator':paginator,
    'agent':agent.object_list,
    'is_paginated': paginator.num_pages > 1,
    'has_next': agent.has_next(),
    'has_previous': agent.has_previous(),
    'current_page': page,
    'next_page': page + 1,
    'previous_page': page - 1,
    'pages': paginator.num_pages,
    'page_numbers': range(paginator.num_pages + 1)[1:],
    'hits' : paginator.count,
    'level':request.session['level'],
    })

"""调用修改显示页"""
def edit(request, a_id):
    """管理员才有权限"""
    if request.session['level'] != "administrators":
        return HttpResponseRedirect('/')
    agent = get_object_or_404(Agent, pk = a_id)
    return render_to_response('edit_a.html', {'agent': agent})


"""删除用户"""
def del_a (request, a_id = ""):
    """管理员才有权限"""
    if request.session['level'] != "administrators":
        return HttpResponseRedirect('/')
    Agent.objects.filter(pk = a_id).delete()
    return HttpResponseRedirect('/alist/')

